package com.woniuxy.project115.kaer.tenant.consumer;

import com.woniuxy.project115.kaer.tenant.entity.OrderLog;
import com.woniuxy.project115.kaer.tenant.entity.ServiceOrder;
import com.woniuxy.project115.kaer.tenant.mapper.OrderLogMapper;
import com.woniuxy.project115.kaer.tenant.mapper.ServiceOrderMapper;
import com.woniuxy.project115.kaer.tenant.util.Data;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * @author HuH
 * @version 1.0
 * @CreatTime 2025-02-24 15:53
 * @description
 */
@Component
public class CompleteOrderConsumer {
    @Resource
    private ServiceOrderMapper serviceOrderMapper;

    @Resource
    private OrderLogMapper orderLogMapper;

    @Resource
    private RedissonClient redissonClient;

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue("evaluate_order_queue"),
                    exchange = @Exchange("delay_ex"),
                    key = "evaluate_order"
            )
    )
    @RabbitHandler
    public void completeOrder(String serviceOrderNum) throws Exception {
        RLock lock = redissonClient.getFairLock(serviceOrderNum);
        try {
            lock.lock();
            ServiceOrder serviceOrder = serviceOrderMapper.selectById(serviceOrderNum);
            if (serviceOrder == null) {
                throw new Exception("订单不存在");
            }
            if (serviceOrder.getState() != Data.SERVICE_ORDER_WAIT_CHECK) {
                return;
            }

            if (serviceOrder.getPayState() == Data.PAY_STATE_PAYED) {//用户已经支付过了
                serviceOrder.setState(Data.SERVICE_ORDER_COMPLETED);
                serviceOrderMapper.updateById(serviceOrder);
            } else {//用户还未支付
                serviceOrder.setState(Data.SERVICE_ORDER_WAIT_PAYMENT);
                serviceOrderMapper.updateById(serviceOrder);
            }

            //更新订单日志
            orderLogMapper.insert(
                    new OrderLog()
                            .setOperator("系统")
                            .setServiceOrderNum(serviceOrderNum)
                            .setOperateTime(LocalDateTime.now())
                            .setOperateType("用户超时未验收，系统自动验收")
            );
        } finally {
            lock.unlock();
        }
    }
}
